﻿using System;
using System.Collections.Generic;
using System.Text;

namespace UDPPunchTest
{
    /// <summary>
    /// Message exchange format between Punch Clients and Punch Client/Server
    /// </summary>
    class PunchMessage
    {
        public string m_command;
        public string m_command_param;
        public Dictionary<string, string> m_lines = new Dictionary<string, string>();

        public const string PEER_ADDRESS_NOT_FOUND = "peer_address_not_found";

        public PunchMessage()
        {
        }

        public PunchMessage(string command, string command_param)
        {
            m_command = command;
            m_command_param = command_param;
        }

        public void addLine(string key, string value)
        {
            m_lines[key] = value;
        }

        public static PunchMessage parseMessage(byte[] msg,int length)
        {
            string recv_string = Encoding.ASCII.GetString(msg, 0, length);
            return parseMessage(recv_string);
        }

        private void parseKeyValueMessage(string recv_string)
        {
            string[] kv_pairs = recv_string.Split('\n');
            foreach (string kv in kv_pairs)
            {
                string[] fields = kv.Split(new char[] { '=' }, 2);
                if (fields.Length > 1)
                {
                    string str = fields[0];
                    string value = fields[1];
                    if (m_command == null)
                    {
                        m_command = str;
                        m_command_param = value;
                    }
                    m_lines[str] = value;
                }
            }
        }

        public static PunchMessage parseMessage(string msg)
        {
            PunchMessage pmsg = new PunchMessage();
            pmsg.parseKeyValueMessage(msg);
            return pmsg;
        }

        internal byte[] serialize()
        {
            string line = m_command + "=" + m_command_param;
            return Encoding.ASCII.GetBytes(line);
        }
    }
}
